import * as categoryApi from '@/api/category.js';

export default {
  namespaced: true,
  state() {
    return {
      categoryList: [],
      subCategoryList: {
        brands: [],
        categories: [],
        goods: [],
        saleProperties: [],
      },
      subCategoryGoodsList: {
        items: [],
        page: 1,
        pageSize: 10,
        counts: 0,
        pages: 1,
      },
      // 商品详情
      productDetail: {},
      // 同类商品推荐
      goodsRelevant: {},
    };
  },
  getters: {
    subCategoryFilters(state) {
      return [{
        id: 'pinpai',
        name: '品牌',
        properties: state.subCategoryList.brands,
      },
      ...state.subCategoryList.saleProperties,
      ];
    },
  },
  mutations: {
    SET_CATEGORY_LIST(state, newValue) {
      state.categoryList = newValue;
    },
    SET_SUB_CATEGORY_LIST(state, newValue) {
      state.subCategoryList = newValue;
    },
    // 懒加载拼接数据
    SET_SUB_CATEGORY_GOODS(state, newValue) {
      state.subCategoryGoodsList = {
        ...newValue,
        items: state.subCategoryGoodsList.items.concat(newValue.items),
      };
    },
    // 重置数据
    RESET_SUB_CATEGORY_GOODS(state, newValue) {
      state.subCategoryGoodsList = newValue;
    },
    // 设置商品详情
    SET_PRODUCT_DETAIL(state, newValue) {
      state.productDetail = newValue;
    },
    // 设置同类商品推荐
    SET_GOODS_RELEVANT(state, newValue) {
      state.goodsRelevant = newValue;
    },
  },
  actions: {
    // 分类页分类列表
    async updateCategoryList({ commit }, id) {
      const res = await categoryApi.getCategoryList(id);
      commit('SET_CATEGORY_LIST', res);
    },
    // 二级分类页分类列表
    async updateSubCategoryList({ commit }, id) {
      const res = await categoryApi.getSubCategoryList(id);
      commit('SET_SUB_CATEGORY_LIST', res);
    },
    // 懒加载二级分类页商品列表
    async updateSubCategoryGoods({ commit }, params) {
      const res = await categoryApi.getSubCategoryGoodsList(params);
      commit('SET_SUB_CATEGORY_GOODS', res);
    },
    // 商品详情
    async updateProductDetail({ commit }, id) {
      const res = await categoryApi.getProductDetail(id);
      commit('SET_PRODUCT_DETAIL', res);
    },
    // 同类商品推荐
    async updateGoodsRelevant({ commit }, params) {
      const res = await categoryApi.getGoodsRelevant(params);
      commit('SET_GOODS_RELEVANT', res);
    },
  },
};
